package com.dm0858.bianmin.mine.network;


import com.socks.library.KLog;

import java.net.Proxy;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * @author 迪迪丶Sir
 * @description Network管理类
 * @e-mail asd969709719@qq.com
 * @since 2020-03-15
 **/
public class NetworkManager {

    private static final int DEFAULT_TIME_OUT = 5;              //连接超时时间
    private static final int DEFAULT_READ_TIME_OUT = 10;        //连接读取超时时间
    private static final int DEFAULT_WRITE_TIME_OUT = 15;       //连接写入超时时间

    private static NetworkManager mInstance;
    private static Retrofit retrofit;
    private static volatile RetrofitService RetrofitService = null;

    public static NetworkManager getInstance() {
        if (mInstance == null) {
            synchronized (NetworkManager.class){
                if (mInstance == null) mInstance = new NetworkManager();
            }
        }
        return mInstance;
    }

    public void init(String url) {


        //初始化OkHttpClient
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(mHeaderInterceptor)
                .addInterceptor(mLogInterceptor)
                .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_WRITE_TIME_OUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .proxy(Proxy.NO_PROXY)
                .build();

        //初始化Retrofit
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static RetrofitService getRequest() {
        if (RetrofitService == null) {
            synchronized (RetrofitService.class) {
                RetrofitService = retrofit.create(RetrofitService.class);
            }
        }
        return RetrofitService;
    }

    /**增加头部信息的拦截器*/
    private Interceptor mHeaderInterceptor = chain -> {
        Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("Content-Type","application/x-www-form-urlencoded");
        builder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.108 Safari/537.36 2345Explorer/8.0.0.13547");
        builder.addHeader("Cache-Control", "max-age=0");
        builder.addHeader("Upgrade-Insecure-Requests", "1");
        builder.addHeader("X-Requested-With", "XMLHttpRequest");
        builder.addHeader("Cookie", "uuid=\"w:f2e0e469165542f8a3960f67cb354026\"; __tasessionId=4p6q77g6q1479458262778; csrftoken=7de2dd812d513441f85cf8272f015ce5; tt_webid=36385357187");
        return chain.proceed(builder.build());
    };

    /**请求访问quest和response拦截器*/
    private Interceptor mLogInterceptor = chain -> {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        KLog.e("----------Request Start----------------");
        KLog.e("| " + request.toString());
        KLog.json("| Response:" + content);
        KLog.e("----------Request End:" + duration + "毫秒----------");
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    };
}
